<?php

namespace App\Http\Admin\Services\Order;

use App\Exceptions\InvalidRequestException;
use App\Http\Api\Services\LogisticsService;
use App\Http\Models\Manu;
use App\Http\Models\Order;
use App\Http\Models\OrderRefundReg;
use App\Http\Services\BaseOrderService;
use App\Lib\PHPExcel\ExcelHandle;
use App\Lib\Zhuzhuyun\Zhuzhuyun;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderService extends BaseOrderService
{
    protected $order_status_arr = [];

    public function __construct()
    {
        $order_status_arr = DB::table('admin_config')->where('conf_key', 'order_status')->first()->conf_val;
        $this->order_status_arr = !empty($order_status_arr) ? json_decode($order_status_arr, true) : [];
    }

    /*
     * 订单修改
     * */
    public function orderEdit($attributes = [])
    {
        $origin_prod_id = !empty($attributes['origin_prod_id']) ? $attributes['origin_prod_id'] : null;
        $cost_price = !empty($attributes['cost_price']) ? $attributes['cost_price'] : null;
        $express_fee = !empty($attributes['express_fee']) ? $attributes['express_fee'] : null;
        $manu_name = !empty($attributes['manu_name']) ? $attributes['manu_name'] : '';
        $start_time = !empty($attributes['start_time']) ? $attributes['start_time'] : null;
        $end_time = !empty($attributes['end_time']) ? $attributes['end_time'] : null;
        $order_id = !empty($attributes['order_id']) ? $attributes['order_id'] : null;
        $refund_reason = !empty($attributes['refund_reason']) ? $attributes['refund_reason'] : null;

        if ((is_null($origin_prod_id) && is_null($order_id)) || (is_null($cost_price) && is_null($refund_reason)) || ($refund_reason && !$order_id)) {
            throw new InvalidRequestException('参数输入有误');
        }
        if ($order_id) {
            if ($refund_reason && !$cost_price) {
                $res = Order::where('order_id', $order_id)->update([
                    'refund_reason' => $refund_reason
                ]);
                return $res;
            } else {
                $res = Order::where('order_id', $order_id)->update([
                    'cost_price' => $cost_price,
                    'express_fee' => $express_fee,
                    'manu_name' => $manu_name,
                    'refund_reason' => $refund_reason
                ]);
                return $res;
            }
        }
        $res = Order::where('origin_prod_id', $origin_prod_id)
            ->whereBetween('create_time', [
                $start_time, $end_time
            ])->update([
                'cost_price' => $cost_price,
                'express_fee' => $express_fee,
                'manu_name' => $manu_name
            ]);
        return $res;
    }


    /*
     * 订单状态统计
     * */
    public function orderStatusCount($conditions = [])
    {
        $query = Order::query();
        $raw = DB::raw('order_status,count(*) as order_count,
            sum(total_amount) as shop_total_amount,
            sum(combo_num*cost_price + express_fee) as cost_total_price'
        );
        //只要备货中 已完成 已发货订单
        $query = $this->simpleConditions($query, $conditions)->whereIn('order_status', [2, 3, 5, 9, 15, 20, 26, 27, 28, 29, 31, 33, 36, 37, 38]);
        $back_query = clone($query);
        $res = $query->select($raw)->groupBy('order_status')->get()->toArray();
        $back_res = $back_query->select($raw)->where('cost_price', '!=', 0)->groupBy('order_status')->get()->toArray();

        $arr = [];
        $arr['总计'] = [
            'order_status_text' => '总计',
            'order_count' => 0,
            'shop_total_amount' => 0,
            'back_shop_total_amount' => 0,
            'back_cost_total_price' => 0,
            'back_order_count' => 0
        ];
        if (count($res) > 0) {
            foreach ($res as $item) {
                $text = $this->mergeOrderStatusToText($item['order_status']);
                if (!isset($arr[$text])) {
                    $arr[$text] = [
                        'order_status_text' => $text,
                        'order_count' => 0,
                        'shop_total_amount' => 0,
                        'back_shop_total_amount' => 0,
                        'back_cost_total_price' => 0,
                        'back_order_count' => 0
                    ];
                }
                $arr[$text]['order_count'] = $arr[$text]['order_count'] + $item['order_count'];
                $arr[$text]['shop_total_amount'] = $arr[$text]['shop_total_amount'] + $item['shop_total_amount'];
                $arr[$text]['back_shop_total_amount'] = $arr[$text]['back_shop_total_amount'] + (collect($back_res)->where('order_status', $item['order_status'])->first()['shop_total_amount'] ?? 0.00);
                $arr[$text]['back_cost_total_price'] = $arr[$text]['back_cost_total_price'] + (collect($back_res)->where('order_status', $item['order_status'])->first()['cost_total_price'] ?? 0.00);
                $arr[$text]['back_order_count'] = $arr[$text]['back_order_count'] + (collect($back_res)->where('order_status', $item['order_status'])->first()['order_count'] ?? 0.00);

                $arr['总计']['order_count'] = $arr['总计']['order_count'] + $item['order_count'];
                $arr['总计']['shop_total_amount'] = $arr['总计']['shop_total_amount'] + $item['shop_total_amount'];
                $arr['总计']['back_shop_total_amount'] = $arr['总计']['back_shop_total_amount'] + (collect($back_res)->where('order_status', $item['order_status'])->first()['shop_total_amount'] ?? 0.00);
                $arr['总计']['back_cost_total_price'] = $arr['总计']['back_cost_total_price'] + (collect($back_res)->where('order_status', $item['order_status'])->first()['cost_total_price'] ?? 0.00);
                $arr['总计']['back_order_count'] = $arr['总计']['back_order_count'] + (collect($back_res)->where('order_status', $item['order_status'])->first()['order_count'] ?? 0.00);
            }
        }


        return collect($arr)->values()->all();
    }

    /*
     * 计算新客 新客数量
     * */
    public function customerCount($conditions = [], $liver = '')
    {
        $query = Order::query();
        //算出日期内顾客总数 电话号码去重
        $raw = DB::raw('distinct(post_tel)');
        $query->select($raw)->where('liver', $liver);
        $query = $this->simpleConditions($query, $conditions);
        $query_clone = clone($query);
        //算出客户数
        $query_unique_phones_count = count($query->get());
        //算出老客数量
        $conditions['start_time'] = !empty($conditions['start_time']) ? $conditions['start_time'] : '2000-01-01 00:00:00';
        $phones_count_ago = count(Order::select($raw)
            ->where('liver', $liver)
            ->where('create_time', '<', $conditions['start_time'])
            ->whereIn('post_tel', $query_clone)->get());

        //算出新客数
        $phones_count_new = $query_unique_phones_count - $phones_count_ago;

        return [
            $query_unique_phones_count,
            $phones_count_new
        ];

    }

    /*
     * 主播订单统计
     * */
    public function OrderLiverCount($conditions = [])
    {
        $query = Order::query();
        $raw = DB::raw('liver,order_status,count(*) as order_count,
            sum(total_amount) as shop_total_price,
            sum(express_fee) as express_total_fee,
            sum(combo_num*cost_price) as total_cost_price, 
            sum(combo_num*cost_price + express_fee) as cost_total_price,
            sum(coupon_amount + shop_coupon_amount) as coupon_total_amount'
        );
        $query->select($raw);
        $query = $this->simpleConditions($query, $conditions);
        $query_filter = clone($query);
        $result = $query->groupBy('liver', 'order_status')->get();
        $result_filter = $query_filter->where('cost_price', '!=', 0)->groupBy('liver', 'order_status')->get()->toArray();


        $final_result = [];
        if (!empty($result)) {
            //新客总数
            $new_total_count = 0;
            //顾客总数
            $total_count = 0;
            $final_result['总计']['name'] = '总计';
            $final_result['总计']['infos'] = [];
            foreach ($result as $item) {
                //添加主播
                if (!$item['liver']) {
                    $item['liver'] = '未知';
                }
                if (!isset($final_result[$item['liver']])) {
                    $final_result[$item['liver']] = [];
                    //算出顾客总数 新客数
                    $count_data = $this->customerCount($conditions, $item['liver']);
                    $final_result[$item['liver']]['name'] = $item['liver'];
                    $final_result[$item['liver']]['customer_total_count'] = $count_data[0];
                    $final_result[$item['liver']]['customer_new_total_count'] = $count_data[1];
                    $total_count = $total_count + $count_data[0];
                    $new_total_count = $new_total_count + $count_data[1];
                }

                //规定插入数组
                $item['order_status_text'] = $this->tranOrderStatusToText($item['order_status']);
                $final_result[$item['liver']]['infos'][] = [
                    'order_status_text' => $item['order_status_text'],
                    'back_cost_total_price' => collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['cost_total_price'] ?? 0,
                    'back_order_count' => collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['order_count'] ?? 0,
                    'back_shop_total_price' => collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['shop_total_price'] ?? 0,
                    'order_count' => $item['order_count'],
                    'coupon_total_amount' => $item['coupon_total_amount'],
                    'shop_total_price' => $item['shop_total_price']
                ];
                if (!count(collect($final_result['总计']['infos'])->where('order_status_text', $item['order_status_text']))) {
                    $final_result['总计']['infos'][] = [
                        'order_status_text' => $item['order_status_text'],
                        'back_cost_total_price' => collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['cost_total_price'] ?? 0,
                        'back_order_count' => collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['order_count'] ?? 0,
                        'back_shop_total_price' => collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['shop_total_price'] ?? 0,
                        'order_count' => $item['order_count'],
                        'coupon_total_amount' => $item['coupon_total_amount'],
                        'shop_total_price' => $item['shop_total_price']
                    ];
                } else {
                    foreach ($final_result['总计']['infos'] as &$total_info) {
                        if ($total_info['order_status_text'] == $item['order_status_text']) {
                            $total_info['back_cost_total_price'] = $total_info['back_cost_total_price'] + (collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['cost_total_price'] ?? 0);
                            $total_info['back_shop_total_price'] = $total_info['back_shop_total_price'] + (collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['shop_total_price'] ?? 0);
                            $total_info['back_order_count'] = $total_info['back_order_count'] + (collect($result_filter)->where('order_status', $item['order_status'])->where('liver', $item['liver'])->first()['order_count'] ?? 0);
                            $total_info['order_count'] = $total_info['order_count'] + $item['order_count'];
                            $total_info['coupon_total_amount'] = $total_info['coupon_total_amount'] + $item['coupon_total_amount'];
                            $total_info['shop_total_price'] = $total_info['shop_total_price'] + $item['shop_total_price'];
                        }
                    }
                }
            }
        }

        $final_result['总计']['customer_total_count'] = $total_count;
        $final_result['总计']['customer_new_total_count'] = $new_total_count;
        $zj = $final_result['总计'];
        $final_result = collect($final_result)->sortByDesc('customer_total_count')->toArray();
        //这样做是为了让总计显示最下面
        unset($final_result['总计']);
        $final_result['总计'] = $zj;
        return collect($final_result)->values()->all();
    }

    /*
     * 订单厂家统计
     * */
    public function OrderManuCount($conditions = [])
    {
        $query = $this->withConditions($conditions);

        $orders = $query->get();

        //查出所有需要统计的厂家
        $marked_manus = Manu::where('is_marked', 1)->get()->pluck('manu_name')->toArray();

        //构建厂家订单数数组
        $result = ['其他' => 0];
        foreach ($marked_manus as $manus) {
            $result[$manus] = 0;
        }
        if (!empty($orders)) {

            foreach ($orders as $order) {
                if (in_array($order['manu_name'], $marked_manus)) {
                    $result[$order['manu_name']]++;
                } else {
                    $result['其他']++;
                }
            }
        }
        return $result;

    }

    /*
     * 订单核算对比
     * */
    public function orderSettCompare($conditions = [])
    {
        $raw = DB::raw('count(s.sett_payment_online) as order_count,
                COUNT(DISTINCT o.order_id) as unique_count,
                sum(s.sett_payment_online) as total_payment_online,
                sum(s.sett_total_amount) as total_sett_amount,
                sum(s.sett_ptfwf) as total_sett_ptfwf
            '
        );
        $query = $this->settConditions($raw, $conditions);

        $result = $query->first();

        $raw = DB::raw('distinct(o.order_id)');
        $query = $this->settConditions($raw, $conditions);
        $new_raw = DB::raw('sum(total_amount) as shop_total_price');

        $result->shop_total_price = Order::select($new_raw)->whereIn('order_id', $query)->first()->shop_total_price;
        //算出期间未发货退款金额


        return $result;
    }

    /*
     * 订单核算列表
     * */
    public function orderSettList($conditions = [])
    {

        $raw = DB::raw("
            o.order_id,o.pid,o.origin_prod_id,o.origin_prod_name,
            o.combo_amount,o.combo_num,o.total_amount,o.create_time,o.order_status,
            o.detail,o.shop_name,s.sett_total_amount,s.sett_payment_online,s.sett_type
          
        ");
        $query = $this->settConditions($raw, $conditions);

        $items = $query->orderBy('create_time', 'desc')->paginate(50);


        foreach ($items as $item) {
            $item['order_status'] = $this->tranOrderStatusToText($item['order_status']);
            switch ($item['sett_type']) {
                case 1:
                    $item['sett_type'] = '微信';
                    break;
                case 2:
                    $item['sett_type'] = '支付宝';
                    break;
                case 3:
                    $item['sett_type'] = '周期';
                    break;
            }
        }

        return $items;
    }

    /*
     * 订单核算条件过滤
     * */
    public function settConditions($raw, $conditions = [])
    {
        $query = Order::query();
        $query->from('admin_orders as o')
            ->select($raw)
            ->leftJoin('admin_order_settlements as s', 'o.order_id', '=', 's.sett_order_id');

        if (!empty($conditions['time_type'])) {
            if (!empty($conditions['start_time'])) {
                $query->where('s.sett_confirmed_at', '>=', $conditions['start_time']);
            }

            if (!empty($conditions['end_time'])) {
                $query->where('s.sett_confirmed_at', '<=', $conditions['end_time']);
            }
        } else {
            if (!empty($conditions['start_time'])) {
                $query->where('o.create_time', '>=', $conditions['start_time']);
            }

            if (!empty($conditions['end_time'])) {
                $query->where('o.create_time', '<=', $conditions['end_time']);
            }
        }

        if (!empty($conditions['sett_type'])) {
            $query->where('s.sett_type', $conditions['sett_type']);
        }


        if (!empty($conditions['order_id'])) {
            $query->where('o.order_id', $conditions['order_id']);
        }

        if (!empty($conditions['order_status'])) {
            if (!is_array($conditions['order_status'])) {
                $conditions['order_status'] = explode(',', $conditions['order_status']);
            }

            if ($conditions['order_status'][0] != 0) {
                $query->whereIn('o.order_status', $conditions['order_status']);
            }
        }

        if (!empty($conditions['shop_id'])) {
            $query->where('o.shop_id', $conditions['shop_id']);
        }

        if (!empty($conditions['no_sett'])) {
            $query->whereNull('s.sett_payment_online');
        }

        return $query->whereNotIn('o.order_status', [1, 4]);

    }


    /*
     * 订单列表
     * */
    public function orderList($conditions = [])
    {

        $query = $this->withConditions($conditions);

        $result = $query->orderBy('create_time', 'desc')->paginate(50);

        $result = $this->filter($result, $conditions);

        return $result;
    }


    /*
     * 条件查询
     * */
    public function withConditions($conditions = [])
    {
        $query = Order::query();
        $raw = DB::raw("
            o.prod_no as prod_no,o.manu_name as order_manu_name,o.order_id,o.pid,o.origin_prod_id,o.origin_prod_name,o.local_order_status,
            o.spec_desc,o.combo_amount,o.combo_num,o.total_amount,o.amount_spec,o.create_time,o.order_status,
            o.post_receiver,o.post_tel,o.province,o.city,o.town,o.detail,tmp_cost_price,
            o.shop_id,o.shop_name,o.logistics_code,o.logistics_from,o.packing_charge,o.return_to_manu,o.refund_is_recovered,
            o.buyer_words,o.seller_words,o.sku_no as sku_no,o.liver,o.created_at,o.updated_at,
            o.manu_name as manu_name,o.cost_price as cost_price,o.express_fee,o.refund_reason,
            o.unline_payment,o.unline_express_fee,o.unline_mark,o.unline_trager
            
        ");
        $query->from('admin_orders as o')
            ->select($raw)
            ->leftJoin('admin_manus as m', 'm.manu_name', '=', 'o.manu_name');

        if (!empty($conditions['start_time'])) {
            $query->where('o.create_time', '>=', $conditions['start_time']);
        }

        if (!empty($conditions['end_time'])) {
            $query->where('o.create_time', '<=', $conditions['end_time']);
        }

        if (!empty($conditions['order_status'])) {
            if (strpos($conditions['order_status'], ',') != false) {
                $status_arr = explode(',', $conditions['order_status']);
                $query->whereIn('order_status', $status_arr);
            } else {
                $query->where('order_status', $conditions['order_status']);
            }
        }

        if (!empty($conditions['origin_prod_id'])) {
            $query->where('o.origin_prod_id', $conditions['origin_prod_id']);
        }

        if (!empty($conditions['order_id'])) {
            $query->where('o.order_id', $conditions['order_id']);
        }

        if (!empty($conditions['shop_id'])) {
            $query->where('o.shop_id', $conditions['shop_id']);
        }

        if (!empty($conditions['liver'])) {
            $query->where('o.liver', $conditions['liver']);
        }

        if (!empty($conditions['post_tel'])) {
            $query->where('o.post_tel', $conditions['post_tel']);
        }

        if (!empty($conditions['refund_reason'])) {
            $query->where('o.refund_reason', 'like', '%' . $conditions['refund_reason'] . '%');
        }

        if (!empty($conditions['post_receiver'])) {
            $query->where('o.post_receiver', $conditions['post_receiver']);
        }

        if (!empty($conditions['detail'])) {
            $tmp_detail = $conditions['detail'];
            $query->where(function ($query) use ($tmp_detail) {
                $query->where('o.detail', 'like', '%' . $tmp_detail . '%')
                    ->orWhere('o.province', 'like', '%' . $tmp_detail . '%')
                    ->orWhere('o.city', 'like', '%' . $tmp_detail . '%')
                    ->orWhere('o.town', 'like', '%' . $tmp_detail . '%');
            });

        }

        if (!empty($conditions['back_status'])) {
            //有回填数据的
            if ($conditions['back_status'] == 1) {
                $query->where('cost_price', '!=', 0);
            }
            //没有回填数据的
            if ($conditions['back_status'] == 2) {
                $query->where('cost_price', '==', 0);
            }
        }

        if (!empty($conditions['manu_name'])) {
            if ($conditions['manu_name'] == '其他') {
                $marked_manus = Manu::where('is_marked', 1)->get()->pluck('manu_name')->toArray();
                $query->where(function ($query) use ($marked_manus) {
                    $query->whereNotIn('m.manu_name', $marked_manus)->orWhereNull('m.manu_name');
                });
            } else {
                $query->where('m.manu_name', $conditions['manu_name']);
            }
        }

        return $query->whereNotIn('o.order_status', [1, 4]);
    }

    /*
     * 订单数据过滤
     * full_addr 地址全称
     * color 颜色
     * size 尺码
     * wither 跟播
     * prod_detail 详细
     * */

    public function filter($arr, $conditions = [], $flag = true)
    {
        if (count($arr) > 0) {
            if ($flag) {
                $phones = $arr->pluck('post_tel');
                $phones = json_encode($phones);
                $fans = file_get_contents('http://fans.youdnr.com/api/fans/list?phone=' . $phones);
                $fans = json_decode($fans, true)['result'];
            }


            foreach ($arr as $item) {
                $item['wither'] = '';
                $item['color'] = '';
                $item['size'] = '';
                $item['specs'] = '';
                $item['prod_detail'] = '';

                $item['full_addr'] = $item['province'] . $item['city'] . $item['town'] . $item['detail'];
                //先根据规格解析
                if (!empty($item['spec_desc'])) {
                    $property_arr = json_decode($item['spec_desc'], true);
                    $item['color'] = !empty($property_arr['颜色']) ? $property_arr['颜色'] : '';
                    $item['size'] = !empty($property_arr['尺码']) ? $property_arr['尺码'] : '';

                    foreach ($property_arr as $p) {
                        $item['specs'] = $item['specs'] . '_' . $p;
                    }
                }

                $pattern = "/[\S|\s]*\+[\S|\s]*\#[\S|\s]*\#[\S|\s]*/";
                if (preg_match($pattern, $item['seller_words'])) {
                    $exp_arr = explode('#', $item['seller_words']);
                    if (!empty($exp_arr[0])) {
                        $wither = explode('+', $exp_arr[0])[1];
                        if ($wither) {
                            $item['wither'] = $wither;
                        }
                    }

                    //再根据备注覆盖
                    if (!empty($exp_arr[2])) {
                        $item['size'] = $exp_arr[2];
                    }
                    if (!empty($exp_arr[3])) {
                        $item['color'] = $exp_arr[3];
                    }
                }
                //详细
                $item['prod_detail'] = $item['origin_prod_name'] . $item['specs'];
                //订单状态
                $item['order_status_text'] = $this->tranOrderStatusToText($item['order_status']);
                //历史订单
                if (!empty($conditions['start_time'])) {
                    $item['history'] = Order::where('post_tel', $item['post_tel'])->where('create_time', '<', $conditions['start_time'])
                        ->where('shop_id', $item['shop_id'])->whereNotIn('order_status', [1, 4])->count();
                } else {
                    $item['history'] = Order::where('post_tel', $item['post_tel'])
                        ->where('shop_id', $item['shop_id'])->whereNotIn('order_status', [1, 4])->count();
                }

                //利润
                $item['profit'] = $item['total_amount'] - $item['cost_price'] - $item['express_fee'];
                //利润率
                $item['profit_rate'] = round($item['profit'] / $item['total_amount'] * 100, 2);
                $item['profit_rate'] = $item['profit_rate'] . '%';

                //是否退回厂家
                $item['return_to_manu'] = !empty($item['return_to_manu']) ? '是' : '否';
                //退款是否收回
                $item['refund_is_recovered'] = !empty($item['refund_is_recovered']) ? '是' : '否';
                //昵称
                if ($flag) {
                    $item['nickname'] = collect($fans)->where('phone', $item['post_tel'])->first()['nickname'] ?? '未知';
                }


            }

        }
        return $arr;
    }

    /*
     * 导出excel
     * */
    public function orderExp($conditions = [])
    {
        $query = $this->withConditions($conditions);

        $result = $query->orderBy('create_time', 'desc')->get();

        $result = $this->filter($result, [], false);

        $guideForm = !empty($conditions['guide_form']) ? $conditions['guide_form'] : 'Normal';

        $title = '订单 ' . $guideForm;

        ExcelHandle::factory($guideForm, $title, $result->toArray())->export();
    }

    /*
  * 导出产品销量excel
  * */
    public function goodsExp($conditions = [])
    {
        $query = $this->withConditions($conditions);

        $result = $query->orderBy('create_time', 'desc')->get();

        $result = $this->filter($result, [], false);

        $result = $result->groupBy(['prod_no', 'size', 'color'])->toArray();

        $data = [];
        $index = 0;
        foreach ($result as $k => $v) {
            $list = $v;
            foreach ($list as $kk => $vv) {
                if (!empty($k)) {
                    foreach ($vv as $kkk => $vvv) {
                        $data[$index]['prod_no'] = $k;
                        $data[$index]['size'] = $kk;
                        $data[$index]['count'] = count($vvv);
                        $data[$index]['manu_name'] = $vvv[0]['order_manu_name'] ?? '';
                        $data[$index]['color'] = $kkk;
                        $index++;
                    }
                }
            }
        }

        ExcelHandle::factory('GoodsCount', '订单-产品销量统计', $data)->export();
    }


    /*
     * 物流任务创建
     * */
    public function logisticsTask($arr = [])
    {
        if (empty($arr)) {
            $arr = ExcelHandle::read();
            if (count($arr) == 0) {
                throw new InvalidRequestException('数据不能为空');
            }
        }

        //做同步到数据库操作
        $logistic = new LogisticsService();
        $logistic->createTaskAndDetail($arr);
        //把解析出来的数组进行归并 公司拼音 => [123,456]
        $tmp_arr = [];
        foreach ($arr as $item) {
            if (!array_key_exists($item['B'], $tmp_arr)) {
                $tmp_arr[$item['B']] = [];
            }
            $tmp_arr[$item['B']][] = $item['A'];
        }
        //开始创建任务
        $final = [];
        $z = new Zhuzhuyun();
        if (!empty($tmp_arr)) {
            foreach ($tmp_arr as $key => $val) {
                $result = $z->createTask($key, implode(',', $val));
                if ($result) {
                    $final[] = [
                        'tag' => $key,
                        'msg' => $result['msg']
                    ];
                }
            }
        }
        //任务入库
        $logistic->logisticsTask($final);

        return $final;
    }

    /*
     * 临时任务创建
     * */
    public function logisticsTmpTask()
    {

        $arr = ExcelHandle::read();
        if (count($arr) == 0) {
            throw new InvalidRequestException('数据不能为空');
        }


        //把解析出来的数组进行归并 公司拼音 => [123,456]
        $tmp_arr = [];
        foreach ($arr as $item) {
            if (!array_key_exists($item['B'], $tmp_arr)) {
                $tmp_arr[$item['B']] = [];
            }
            $tmp_arr[$item['B']][] = $item['A'];
        }
        //开始创建任务
        $final = [];
        $z = new Zhuzhuyun();
        if (!empty($tmp_arr)) {
            foreach ($tmp_arr as $key => $val) {
                $result = $z->createTask($key, implode(',', $val));
                if ($result) {
                    $final[] = [
                        'tag' => $key,
                        'msg' => $result['msg']
                    ];
                }
            }
        }

        return $final;
    }

    /*
     * 物流任务查询
     * */
    public function logisticsQuery($taskname)
    {
        $z = new Zhuzhuyun();

        if (!$taskname) {
            throw new InvalidRequestException('缺少task_id');
        }

        $i = 1;
        $total = 0;
        $list = [];
        do {
            $res = $z->queryTask($i, $taskname);

            if ($res['code']) {
                if ($res['msg']['jindu'] == 100) {
                    foreach ($res['msg']['list'] as $it) {
                        $list[] = $it;
                    }
                    $total = $res['msg']['totalpage'];
                }
            }
            $i++;
        } while ($i <= $total);

        return $list;
    }

    /*
     * 物流导出
     * */
    public function logisticsExp($tasks)
    {

        if (!is_array($tasks)) {
            $tasks = json_decode($tasks, true);
        }
        $data = [];
        foreach ($tasks as $task) {
            $tmp = $this->logisticsQuery($task);
            $data = array_merge($tmp, $data);
        }

        $arr = [];
        if (!empty($data)) {
            foreach ($data as $it) {
                $arr[] = [
                    'kddh' => $it['kddh'],
                    'wuliuzhuangtai' => $it['wuliuzhuangtai'],
                    'kdgs' => $it['kdgs'],
                    'zuixinshijian' => $it['zuixinshijian'],
                    'xiangxiwuliu' => $it['xiangxiwuliu']
                ];
            }
        }


        $title = '物流表格';
        ExcelHandle::factory('Logistics', $title, $arr)->export();
    }

    public function orderSettExp($conditions = [])
    {
        $raw = DB::raw("
            o.order_id,o.pid,o.origin_prod_id,o.origin_prod_name,
            o.combo_amount,o.combo_num,o.total_amount,o.create_time,o.order_status,
            o.detail,o.shop_name,s.sett_total_amount,s.sett_payment_online,s.sett_type,s.sett_ptfwf
          
        ");

        $query = $this->settConditions($raw, $conditions);

        $items = $query->orderBy('create_time', 'desc')->get();

        foreach ($items as $item) {
            $item['order_status'] = $this->tranOrderStatusToText($item['order_status']);
            switch ($item['sett_type']) {
                case 1:
                    $item['sett_type'] = '微信';
                    break;
                case 2:
                    $item['sett_type'] = '支付宝';
                    break;
                case 3:
                    $item['sett_type'] = '周期';
                    break;
            }
        }

        $guideForm = !empty($conditions['guide_form']) ? $conditions['guide_form'] : 'Normal';

        $title = '订单 ' . $guideForm;

        ExcelHandle::factory($guideForm, $title, $items->toArray())->export();
    }


    /*退款登记*/

    public function storeRefund($conditions = [])
    {

        Order::where('order_id', $conditions['order_id'])->update([
            'local_order_status' => intval($conditions['status']),
            'unline_trager'=>$conditions['unline_trager'],
            'unline_payment'=>$conditions['unline_payment'],
            'unline_express_fee'=>$conditions['unline_express_fee'],
            'unline_mark'=>$conditions['unline_mark'],
        ]);

        return true;

    }

    public function orderTip($conditions = [], $compare = [])
    {
        $raw = DB::raw('order_status,sum(total_amount) as price');
        $query = Order::select($raw);

        $query = $this->simpleConditions($query, $conditions);

        $data = $query->groupBy('order_status')->get()->toArray();

        $total_sett_amount = $compare['total_sett_amount'];
        $total_sett_ptfwf = $compare['total_sett_ptfwf'];

        $fin_data = [
            'total_amount' => 0,
            'wfhtk' => 0,
            'yfhtk' => 0,
            'sjlr' => 0,
            'sjsdjs' => $total_sett_amount ?? 0,
            'wfhtk_rate' => '',
            'yfhtk_rate' => '',
            'zzcj_rate' => '',
            'jswdz' => '',
            'total_sett_ptfwf' => abs($total_sett_ptfwf),
        ];

        if (count($data) > 0) {
            foreach ($data as $item) {
                if ($item['order_status'] == 21) {
                    //未发货退款成功
                    $fin_data['wfhtk'] = $item['price'];
                }
                if ($item['order_status'] == 22 || $item['order_status'] == 39) {
                    //已发货退款成功
                    $fin_data['yfhtk'] = $fin_data['yfhtk'] + $item['price'];
                }
                $fin_data['total_amount'] = $fin_data['total_amount'] + $item['price'];
                if ($item['order_status'] != 21 && $item['order_status'] != 22 && $item['order_status'] != 39) {
                    $fin_data['sjlr'] = $fin_data['sjlr'] + $item['price'];
                }
            }
            try {
                //未发货退款率： =未发货退款成功/付款金额   $item['profit_rate'] = round($item['profit'] / $item['total_amount'] * 100, 2);
                $fin_data['wfhtk_rate'] = round($fin_data['wfhtk'] / $fin_data['total_amount'] * 100, 2) . '%';

                //已发货退款率：=已发货退款成功/(付款金额-未发货退款成功)
                $fin_data['yfhtk_rate'] = round($fin_data['yfhtk'] / ($fin_data['total_amount'] - $fin_data['wfhtk']) * 100, 2) . '%';

                //最终成交率：= 平台应该结算/(付款金额-未发货退款成功)
                $fin_data['zzcj_rate'] = round($fin_data['sjlr'] / ($fin_data['total_amount'] - $fin_data['wfhtk']) * 100, 2) . '%';

                //结算未到账：=平台应该结算-实际收到结算-平台服务费
                $fin_data['jswdz'] = round($fin_data['sjlr'] - $total_sett_amount - $total_sett_ptfwf, 2);
            } catch (\Exception $e) {

            }

        }

        return $fin_data;
    }

    public function orderImport()
    {
        $arr = ExcelHandle::read();

        if (count($arr) == 0) {
            throw new InvalidRequestException('数据不能为空');
        }
        $i = 0;
        foreach ($arr as $item) {
            if (!empty($item['A'])) {
                $order_id = $item['A'];
                $it = [];
                if (!empty($item['B'])) {
                    $it['logistics_code'] = $item['B'];
                }
                if (!empty($item['C'])) {
                    $it['cost_price'] = $item['C'];
                }
                if (!empty($item['D'])) {
                    $it['express_fee'] = $item['D'];
                }
                if (!empty($item['E'])) {
                    $it['packing_charge'] = $item['E'];
                }
                if (!empty($item['F'])) {
                    $it['return_to_manu'] = $item['F'];
                }
                if (!empty($item['G'])) {
                    $it['refund_is_recovered'] = $item['G'];
                }
                if (!empty($item['H'])) {
                    $it['logistics_from'] = $item['H'];
                }
                if (!empty($item['I'])) {
                    $it['manu_name'] = $item['I'];
                }


                $flag = Order::where('order_id', $order_id)->exists();
                if ($flag) {
                    Order::where('order_id', $order_id)->update($it);
                    $i++;
                }

            }
        }
        return $i;
    }

    /*
     * 退货订单
     */
    public function refundReg($condition    =   []){

        $modal  =   OrderRefundReg::whereNotNull('order_id');

        if(!empty($condition['phone'])){
            $modal  =   $modal->where('post_tel','like',"%".$condition['phone']."%");
        }
        if(!empty($condition['order_id'])){
            $modal  =   $modal->where('order_id',$condition['order_id']);
        }
        if(!empty($condition['logistics_code'])){
            $modal  =   $modal->where('logistics_code','like',"%".$condition['logistics_code']."%");
        }
        if(!empty($condition['post_receiver'])){
            $modal  =   $modal->where('post_receiver','like',"%".$condition['post_receiver']."%");
        }

        $data   =   $modal->orderBy('reg_time','desc')->paginate(50);



        foreach ($data as $item){
            //订单状态
            $item['order_status_text'] = $this->tranOrderStatusToText($item['order_status']);

        }

        return $data;

    }

    /*
     * 退货登记
     */
    public function register($condition    =   []){

        if(empty($condition['order_id']) || empty($condition['reg_person']) || empty($condition['logistics_code'])){
            throw new InvalidRequestException('数据不能为空');
        }

        $order   =    Order::where('order_id',$condition['order_id'])->first();

        if(!$order){
            throw new InvalidRequestException('暂无该订单');
        }


        //先根据规格解析
        if (!empty($order['spec_desc'])) {
            $property_arr = json_decode($order['spec_desc'], true);
            $order['color'] = !empty($property_arr['颜色']) ? $property_arr['颜色'] : '';
            $order['size'] = !empty($property_arr['尺码']) ? $property_arr['尺码'] : '';

            foreach ($property_arr as $p) {
                $order['specs'] = $order['specs'] . '_' . $p;
            }
        }

        $tmp    =   [];
        $tmp['order_id']        =   $order['order_id'];
        $tmp['shop_id']         =   $order['shop_id'];
        $tmp['shop_name']       =   $order['shop_name'];
        $tmp['post_receiver']   =   $order['post_receiver'];
        $tmp['post_tel']        =   $order['post_tel'];
        //详细
        $tmp['detail']          =   $order['origin_prod_name'] . $order['specs'];
        $tmp['logistics_code']  =   $condition['logistics_code'];
        $tmp['reg_person']      =   $condition['reg_person'];
        $tmp['reg_time']        =   date("Y-m-d H:i:s");
        $tmp['stock']           =   1;
        $tmp['color']           =   $order['color'];
        $tmp['size']            =   $order['size'];
        $tmp['origin_prod_name']=   $order['origin_prod_name'];
        $tmp['specs']           =   $order['origin_prod_name'].'-'.$order['color'].'-'.$order['size'];
        $tmp['prod_no']         =   $order['prod_no'];
        $tmp['cost_price']      =   $order['cost_price'];
        $tmp['combo_amount']    =   $order['combo_amount'];//售价
        $tmp['manu_name']       =   $order['manu_name'];//厂家
        $tmp['order_status']    =   $order['order_status'];//状态
        $tmp['create_time']     =   $order['create_time'];//下单时间

        //查重
        $exists =   OrderRefundReg::where('order_id',$condition['order_id'])->exists();

        if($exists){
            OrderRefundReg::where('order_id',$condition['order_id'])->update($tmp);
        }else{
            OrderRefundReg::create($tmp);
        }
        return;

    }


    /*
     *售卖登记
     */
    public function saleRegister($condition    =   []){

        if(empty($condition['order_id'])){
            throw new InvalidRequestException('参数不能为空');
        }
        unset($condition['token']);
        OrderRefundReg::where('order_id',$condition['order_id'])->update($condition);
        if(!empty($condition['color'] ) || !empty($condition['size'])){
            $order  =  OrderRefundReg::where('order_id',$condition['order_id'])->first();
            $specs  =   $order['origin_prod_name'].'-'.$order['color'].'-'.$order['size'];
            OrderRefundReg::where('order_id',$order['order_id'])->update(['specs'=>$specs]);
        }
        return ;

    }

    /*
    * 退货订单导出
    * */
    public function refundExport($condition =   [])
    {

        $title = '退货订单';
        if(!empty($condition['type'])){
            $data  =   OrderRefundReg::whereNotNull('order_id')->orderBy('reg_time','desc')->get()->toArray();

            foreach ($data as $k => $v){
                //订单状态
                $v['order_status_text'] = $this->tranOrderStatusToText($v['order_status']);
                //进度
                $v['progress_text'] = $this->tranOrderProgressToText($v['progress']);
                $data[$k]   =   $v;
            }
            ExcelHandle::factory('OrderRefund1', $title, $data)->export();
        }else{
            //统计
            $data   =   OrderRefundReg::select(['manu_name','origin_prod_name','color','size',DB::raw('sum(stock) as total_stock')])->where('stock','>',0)->groupBy('manu_name','origin_prod_name','color','size')->get()->toArray();
            ExcelHandle::factory('OrderRefund', $title, $data)->export();
        }





    }



    /*
     *厂家打印记录订单
     */
    public function printOrder($condition   =   []){
        $arr = ExcelHandle::read();

        if (count($arr) == 0) {
            throw new InvalidRequestException('数据不能为空');
        }
        $tmp =   [];
        //A订单号、B运单号、C收件人姓名、D收件人手机号、E所在省份、F所在城市、G所在地区、H详细地址

        if(!empty($condition['upType'])){     //复合订单处理
            foreach ($arr as $item) {
                if (!empty($item['B'])) {
                    $it = [];
                    $arr    =   explode(",",$item['A']);    //分解
                    foreach ($arr as $order_id){
                        if(!empty($order_id)){
                            $it['order_id'] = $order_id;
                            $it['logistics_code'] = $item['B'];
                            $it['post_receiver'] = $item['C'];
                            $it['post_tel'] = $item['D'];
                            $it['address'] = $item['F'].$item['G'].$item['H'];
                            array_push($tmp,$it);
                        }
                    }
                }
            }

        }else{
            foreach ($arr as $item) {
                if (!empty($item['B'])) {
                    $it = [];
                    $it['order_id'] = $item['A'];
                    $it['logistics_code'] = $item['B'];
                    $it['post_receiver'] = $item['C'];
                    $it['post_tel'] = $item['D'];
                    $it['address'] = $item['F'].$item['G'].$item['H'];
                    array_push($tmp,$it);
                }
            }
        }

        return $tmp;
    }

    /*
    *回填订单
    */
    public function backOrder(){
        $arr = ExcelHandle::read();

        if (count($arr) == 0) {
            throw new InvalidRequestException('数据不能为空');
        }
        $tmp =   [];
        //A订单号、B运单号、C收件人姓名、D收件人手机号、E详细地址
        foreach ($arr as $item) {
            if (!empty($item['B'])) {
                $it = [];
                $it['order_id'] = $item['A'];
                $it['logistics_code'] = $item['B'];
                $it['post_receiver'] = $item['C'];
                $it['post_tel'] = $item['D'];
                $it['address'] = $item['E'];
                array_push($tmp,$it);
            }
        }
        return $tmp;
    }


    /*
     * delete
     */
    public function delete($id){

        if(empty($id))  throw new InvalidRequestException('删除失败');

        OrderRefundReg::where('id',$id)->delete();

        return;

    }


}
